package com.briup.searchengine.handle;

import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.util.Bytes;
import org.apache.hadoop.io.BytesWritable;
import org.apache.hadoop.io.MapWritable;

import java.util.Map;
import java.util.NavigableMap;

/**
 * @author adam
 * @date 2022/12/20
 */
public class HbaseUtils {
   public  static final byte[] NONE = "".getBytes();

    //根据列族名和列名获取值
    public static byte[] getValueByFamilyAndCol(Result value, String family, String col) {
        Cell cell = value.getColumnLatestCell(family.getBytes(), col.getBytes());
        if (cell == null || cell.getValueLength() < 1) {
            return NONE;
        }
        return Bytes.copy(cell.getValueArray(), cell.getValueOffset(), cell.getValueLength());
    }

    //获取列族下 列的个数
    public static int countByFamily(Result value, String family) {
        NavigableMap<byte[], byte[]> map = value.getFamilyMap(family.getBytes());
        return map.size();
    }

    //获取列族下的所有数据
    public static  MapWritable getMapByFamily(Result value, String family) {
        // 构建一个Map
        MapWritable map = new MapWritable();
        NavigableMap<byte[], byte[]> navigableMaps = value.getFamilyMap(family.getBytes());
        for (Map.Entry<byte[], byte[]> entry : navigableMaps.entrySet()) {
            byte[] key = entry.getKey();
            byte[] value1 = entry.getValue();

            map.put(new BytesWritable(key), new BytesWritable(value1));
        }
        return map;
    }
}
